<style>
    .add_user_table,.edituser_role_table{
        margin: 15px auto;
    }
    .add_user_table tr,.edituser_role_table tr{
        line-height: 45px;
    }
    .add_user_table tr td:nth-child(2){
        text-align:left;
        width:70%;
    }
    .dialog-button {
        text-align: center;
    }
</style>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'center',border:false">
        <!-- Begin of toolbar -->
        <div id="User-toolbar">
            <div class="wu-toolbar-button">
                <a href="#" class="easyui-linkbutton" iconCls="icon-add" id="adduser" onclick="openAdd()" plain="true">添加</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-lock" id="lock" onclick="batcheditStatus(0)" plain="true">批量锁定</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-lock" id="lock" onclick="batcheditStatus(1)" plain="true">批量解锁</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-reload"  onclick="searchUserGrid()"
                   plain="true">刷新</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-edit" id="resetpwd" onclick="batchresetpwd()" plain="true">批量重置密码</a>
                <a href="#" class="easyui-linkbutton" iconCls="icon-back" onclick="removeTab()" plain="true">返回</a>
            </div>
            <div class="wu-toolbar-search">
                <label>用户名：</label><input class="easyui-textbox" type="text" name="user"
                                          data-options="prompt:'用户名'" style="width:240px"></input>
                <a href="#" class="easyui-linkbutton" iconCls="icon-search" id="queryuser" onclick="searchUserGrid()">开始检索</a>
            </div>
        </div>
        <!-- End of toolbar -->
        <table id="User-datagrid" toolbar="#User-toolbar" class="easyui-datagrid">
        </table>
    </div>
</div>
<!-- Begin of easyui-dialog -->
<div id="user-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="user-add-form" method="post">
        <table class="add_user_table">
            <tr>
                <td width="60">用户名:</td>
                <td><input type="text" name="add_username" class="easyui-textbox" style="width:160px;height:25px;"/></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" class="easyui-textbox" style="width:160px;height:25px;" /></td>
            </tr>
            <tr>
                <td>确认密码:</td>
                <td><input type="password" name="confirmpwd" class="easyui-textbox" style="width:160px;height:25px;" /></td>
            </tr>
        </table>
    </form>
</div>
<!-- End of easyui-dialog -->
<!-- -->
<div id="edituserrole-dialog" class="easyui-dialog" data-options="closed:true,iconCls:'icon-save'"
     style="width:400px; padding:10px;">
    <form id="edituser-role-form" method="post">
        <table class="edituser_role_table">
            <tr>
                <td width="100px">用户名称:</td>
                <td>
                    <input class="easyui-textbox" type="text" name="edituser_role_name" readonly="readonly" style="width:120px;height:25px;"></input>
                </td>
            </tr>
            <tr>
                <td>角色：</td>
                <td>
                    <input id="rolelist" name="rolelist"  style="width:180px;height:25px;"  class="easyui-combobox" >
                </td>
            </tr>
        </table>
    </form>
</div>
<!-- -->
<script type="text/javascript">
    var userid = -1;
    $(function () {
        $('#User-datagrid').datagrid({
            url: getUserListByPageUrl,
            rownumbers: true,
            pagination: true,
            fitColumns: true,
            fit: true,
            singleSelect: false,
            pageSize: 10,
            pageList: [5, 20, 50],
            remoteSort: true,
            multiSort: true,
            columns: [[
                {field:'ck',checkbox:"true"},
                {field: 'id', title: 'ID', align: 'center', width: 40},
                {field: 'username', title: '用户名', width: 60, align: 'center'},
                {field: 'logintime', title: '最后登录时间', width: 150, align: 'center', formatter: format_loginTime},
                {field: 'loginip', title: '最后登录IP', width: 70, align: 'center'},
                {field: 'lock', title: '账号状态', width: 60, align: 'center', formatter: showLock},
                {field: 'operation', title: '操作', width: 180, align: 'center', formatter: showUserOptBtn}
            ]],
            queryParams: {
                username: ""
            },
            onLoadSuccess: function (data) {
                $("a[name='resetpwd']").linkbutton({plain: true, iconCls: 'icon-edit'});
                $("a[name='lock']").linkbutton({plain: true, iconCls: 'icon-lock'});
                $("a[name='disRole']").linkbutton({plain: true, iconCls: 'icon-sum'});
            }
        });
    });

    //按条件查询表格数据
    function searchUserGrid() {
        var queryParams = $('#User-datagrid').datagrid('options').queryParams;
        queryParams.username = $.trim($('input[textboxname=user]').textbox('getValue'));
        $('#User-datagrid').datagrid('reload');
    }

    //显示状态
    function showLock(value, row, index) {
        if (value == 0) {
            return "正常";
        } else {
            return "锁定";
        }
    }

    //显示操作按钮
    function showUserOptBtn(value, row, index) {
        //按条件显示相应按钮
        if(row['lock'] == 0){
            return "<a href='#' onclick='disRole(" + index + ")' class='easyui-linkbutton' id='disRole' name='disRole'>分配角色</a>&nbsp;" +
                    "<a href='#' onclick='resetpwd(" + index + ")' class='easyui-linkbutton'id='resetpwd' name='pwd'>重置密码</a>&nbsp;" +
                    "<a href='#' onclick='editStatus(" + index + ")' class='easyui-linkbutton' id='lock' name='lock'>锁定用户</a>";
        }else{
             return "<a href='#' onclick='disRole(" + index + ")' class='easyui-linkbutton' id='disRole' name='disRole'>分配角色</a>&nbsp;" +
                    "<a href='#' onclick='resetpwd(" + index + ")' class='easyui-linkbutton' id='resetpwd' name='pwd'>重置密码</a>&nbsp;" +
                    "<a href='#' onclick='editStatus(" + index + ")' class='easyui-linkbutton' id='lock' name='lock'>解除锁定</a>";
        }
    }

    function initMultipleCombobox(id){
        var value = "";
        $('#'+id).combobox({
            url:getRoleListUrl,
            method:'post',
            panelHeight:200,//设置为固定高度，combobox出现竖直滚动条
            valueField:'id',
            textField:'role_name',
            multiple:true,
            formatter: function (row) {
                var opts = $(this).combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function () {
                var opts = $(this).combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true);
                })
            },
            onSelect: function (row) {
                var opts = $(this).combobox('options');
                $("#"+id).val($(this).combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {
                var opts = $(this).combobox('options');
                $("#"+id).val($(this).combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            }
        });
    }

    function disRole(rowIndex){
        $('#User-datagrid').datagrid('selectRow',rowIndex);
        rows = $('#User-datagrid').datagrid('getSelections');
        if (rows.length != 1) {
            return;
        }
        //获取当前选中行的索引
        selectedRowIndex = $('#User-datagrid').datagrid('getRowIndex', $('#User-datagrid').datagrid('getSelected'));
        //判断当前按钮所在行与当前选中行是否一致
        if (rowIndex == selectedRowIndex) {
            row = $('#User-datagrid').datagrid('getSelected');
            if (row) {
                userid = row['id'];
                $('input[textboxname=edituser_role_name]').textbox('setValue', row['username']);
                initMultipleCombobox('rolelist');
                //获取当前用户的角色值
                $.ajax({
                    url:getUserRoleUrl,
                    datatype:'json',
                    type:'post',
                    async:false,
                    data:'userid='+userid,
                    success:function(result){
                        if(result.length > 0){
                            role_ids = [];
                            for(i=0;i<result.length;i++){
                                role_ids.push(result[i].role_id);
                            }
                            //初始化下拉多选框
                            $('#rolelist').combobox('setValues',role_ids);
                        }
                    }
                });
                $('#edituserrole-dialog').dialog({
                    closed: false,
                    modal: true,
                    title: "编辑用户角色",
                    top: 30,
                    buttons: [{
                        text: '确定',
                        iconCls: 'icon-ok',
                        handler: doSaveUserRole
                    }, {
                        text: '取消',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#edituserrole-dialog').dialog('close');
                        }
                    }]
                });
            }
        }
    }
    function doSaveUserRole(){
        $("#edituser-role-form").ajaxSubmit({
            url: doSaveUserRoleUrl,
            type: "post",
            dataType: "json",
            beforeSubmit: function (arr, $form, options) {
                //先清空要提交的所有数据
                arr.splice(0,arr.length);
                arr.push({'name':'userid','value':userid,'type':'hidden','required':false});
                arr.push({'name':'rolelist','value':$('#rolelist').combobox('getValues'),'type':'hidden','required':false});
            },
            //提交成功后的回调函数
            success: function (result, status, xhr, $form) {
                $.messager.show({
                    title:'系统提示',
                    msg:result.msg,
                    timeout:500,
                    showType:'slide'
                });
                if(result.errorCode == 0){
                    $('#User-datagrid').datagrid('reload');
                    $('#edituserrole-dialog').dialog('close');
                }
            },
            error: function (xhr, status, error, $form) {
            },
            complete: function (xhr, status, $form) {
            }
        });
    }
    //重置密码
    function resetpwd(rowIndex) {
        rows = $('#User-datagrid').datagrid('getSelections');
        if (rows.length != 1){
            return;
        }
        //获取当前选中行的索引
        selectedRowIndex = $('#User-datagrid').datagrid('getRowIndex', $('#User-datagrid').datagrid('getSelected'));
        //判断当前按钮所在行与当前选中行是否一致
        if (rowIndex == selectedRowIndex) {
            row = $('#User-datagrid').datagrid('getSelected');
            if (row) {
                $.ajax({
                    url: resetPwdUrl,
                    type: "post",
                    dataType: "json",
                    data: 'ids=' + row['id'],
                    success: function (result) {
                        $.messager.show({
                            title:'系统提示',
                            msg:result.msg
                        });
                    }, error: function () {
                    }
                });
            }
        }
    }

    //批量重置密码
    function batchresetpwd() {
        rows = $('#User-datagrid').datagrid('getSelections');
        if (rows.length == 0){
            $.messager.show({
                title:'系统提示',
                msg:'请先选择要操作的数据'
            });
            return;
        }
        ids = "";
        for(i=0;i<rows.length;i++)
        {
            ids = ids + rows[i]['id'] + ",";
        }
        ids = ids.substring(0,ids.length-1);
        $.ajax({
            url: resetPwdUrl,
            type: "post",
            dataType: "json",
            data: 'ids=' + ids,
            success: function (result) {
                $.messager.show({
                    title:'系统提示',
                    msg:result.msg
                });
                $('#User-datagrid').datagrid('reload');
            }, error: function () {
            }
        });
    }

    //修改系统用户状态
    function editStatus(rowIndex){
        rows = $('#User-datagrid').datagrid('getSelections');
        if (rows.length != 1){
            return;
        }
        //获取当前选中行的索引
        selectedRowIndex = $('#User-datagrid').datagrid('getRowIndex', $('#User-datagrid').datagrid('getSelected'));
        //判断当前按钮所在行与当前选中行是否一致
        if (rowIndex == selectedRowIndex) {
            row = $('#User-datagrid').datagrid('getSelected');
            if (row) {
                $.ajax({
                    url: editUserStatusUrl,
                    type: "post",
                    dataType: "json",
                    data: 'ids=' + row['id'] + '&lock=' + row['lock'],
                    success: function (result) {
                        $.messager.show({
                            title:'系统提示',
                            msg:result.msg
                        });
                        $('#User-datagrid').datagrid('reload');
                    }, error: function () {
                    }
                });
            }
        }
    }

    //批量修改系统用户状态
    function batcheditStatus(lock){
        rows = $('#User-datagrid').datagrid('getSelections');
        if (rows.length == 0){
            $.messager.show({
                title:'系统提示',
                msg:'请先选择要操作的数据'
            });
            return;
        }
        ids = "";
        for(i=0;i<rows.length;i++)
        {
            ids = ids + rows[i]['id'] + ",";
        }
        ids = ids.substring(0,ids.length-1);
        $.ajax({
            url: editUserStatusUrl,
            type: "post",
            dataType: "json",
            data: 'ids=' + ids + '&lock=' + lock,
            success: function (result) {
                $.messager.show({
                    title:'系统提示',
                    msg:result.msg
                });
                $('#User-datagrid').datagrid('reload');
            }, error: function () {
            }
        });
    }

    //格式化日期列
    function format_loginTime(value, row, index) {
        if(value != 0) {
            return toDateString(value * 1000);
        }else{
            return "";
        }
    }

    //添加用户
    function addUser() {
        if($.trim($('input[textboxname=add_username]').textbox('getValue'))==""){
            $.messager.show({
                title:'系统提示',
                msg:"用户名没有填写"
            });
            $('input[textboxname=add_username]').textbox().next('span').find('input').focus();
            return;
        }

        if($.trim($('input[textboxname=password]').textbox('getValue'))==""){
            $.messager.show({
                title:'系统提示',
                msg:"密码没有填写"
            });
            $('input[textboxname=password]').textbox().next('span').find('input').focus();
            return;
        }
        if($.trim($('input[textboxname=confirmpwd]').textbox('getValue'))==""){
            $.messager.show({
                title:'系统提示',
                msg:"确认没有填写"
            });
            $('input[textboxname=confirmpwd]').textbox().next('span').find('input').focus();
            return;
        }
        if($.trim($('input[textboxname=confirmpwd]').textbox('getValue'))!=$.trim($('input[textboxname=password]').textbox('getValue'))){
            $.messager.show({
                title:'系统提示',
                msg:"密码与确认密码不一致"
            });
            $('input[textboxname=confirmpwd]').textbox().next('span').find('input').focus();
            return;
        }
        var usermsg,isExistUser;
        $.ajax({
            url: checkUserUrl,
            type: "post",
            async: false,
            dataType: "json",
            data: 'username=' + $.trim($('input[textboxname=add_username]').textbox('getValue')),
            success: function (result) {
                debugger;
                usermsg = result.msg;
                isExistUser = result.isExist;
            }, error: function () {
            }
        });
        if(isExistUser){
            $.messager.show({
                title:'系统提示',
                msg:usermsg
            });
            $('input[textboxname=add_username]').textbox().next('span').find('input').focus();
            return;
        }

        $("#user-add-form").ajaxSubmit({
            url: SaveUserUrl,
            type: "post",
            dataType: "json",
            beforeSubmit: function (arr, $form, options) {
            },
            //提交成功后的回调函数
            success: function (result, status, xhr, $form) {
                $.messager.show({
                    title:'系统提示',
                    msg:result.msg,
                    timeout:500,
                    showType:'slide'
                });
                if(result.errorCode == 0){
                    $('input[textboxname=add_username]').textbox('setValue','');
                    $('input[textboxname=confirmpwd]').textbox('setValue','');
                    $('input[textboxname=password]').textbox('setValue','');
                    $('input[textboxname=add_username]').textbox().next('span').find('input').focus();
                    $('#User-datagrid').datagrid('reload');
                }
            },
            error: function (xhr, status, error, $form) {
            },
            complete: function (xhr, status, $form) {
            }
        });
    }

    // 打开添加窗口
    function openAdd() {
        $('#user-add-form').form('clear');
        $('#user-dialog').dialog({
            closed: false,
            modal: true,
            title: "添加用户",
            buttons: [{
                text: '确定',
                iconCls: 'icon-ok',
                handler: addUser
            }, {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    $('#user-dialog').dialog('close');
                }
            }]
        });
    }
</script>